package cn.cloudreal.cbms.budget.action;

import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.budget.service.BudgetListService;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.log.service.OptLogService;
import cn.cloudreal.cbms.vo.CostSubTypeBudget;
import cn.cloudreal.cbms.vo.CostTypeBudget;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.FundBudget;
import cn.cloudreal.cbms.vo.Log;
import cn.cloudreal.cbms.vo.SourcePlanYear2;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

public class BudgetListAction extends ActionSupport
{

    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(BudgetListAction.class);

    /** 服务 */
    BudgetListService budgetListService;

    /** 服务 */
    OptLogService optLogService;

    List<CostTypeBudget> costTypeBudgets;

    List<String> years;

    FundBudget fbParam;

    SourcePlanYear2 sourcePlanYear;

    List<SourcePlanYear2> sourcePlanYears;

    /** 当前页 */
    int currentPage;

    /** 分页对象 */
    PageBean page;

    /**
     * 预算类型列表
     * 
     * @return
     * @throws Exception
     */
    public String budgetList()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter CastDetailAction budgetList() method, return String");
        }

        try
        {
            // 获取当前session对象中所属城市
            UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute(Constants.SESSIONPRKEY);
            // 默认东莞
            String userInfoCity = "DG";
            // 非空
            if (null != userInfo)
            {
                //
                if (userInfo.getUserRole() != null)
                {

                    // 非空重置
                    if (userInfo.getUsercity() != null)
                    {
                        if (!"".equals(userInfo.getUsercity()))
                        {
                            userInfoCity = userInfo.getUsercity();
                        }
                    }
                    // 操作范围
                    String roleRange = userInfo.getUserRole().getRoleRange();
                    //
                    if (roleRange != null)
                    {

                        // 省
                        if ("1".endsWith(roleRange))
                        {
                            // userInfoCity = null;
                        }
                    }
                }
            }

            // 年份
            years = budgetListService.getYearsByCity(userInfoCity);
            if (years != null)
            {
                if (years.size() != 0)
                {
                    // 预算
                    costTypeBudgets = new ArrayList<CostTypeBudget>();
                    // 查询费用类型
                    List<Dictionary> costTypes = DatadicContext.getInstance()
                            .getDicDataListByCode("FYLX");
                    //
                    CostTypeBudget totalCostTypeBudget = new CostTypeBudget();
                    // 设置费用类型名称
                    totalCostTypeBudget.setCostTypeName("合计");
                    //
                    List<CostSubTypeBudget> totalCostSubTypeBudgets = new ArrayList<CostSubTypeBudget>();
                    //
                    CostSubTypeBudget totalCostSubTypeBudget = new CostSubTypeBudget();
                    // 遍历
                    for (int i = 0; i < costTypes.size(); i++)
                    {
                        // 字典对象
                        Dictionary costType = costTypes.get(i);
                        // 实例化
                        CostTypeBudget costTypeBudget = new CostTypeBudget();
                        // 设置费用类型名称
                        costTypeBudget.setCostTypeName(costType.getDatavalue());
                        // 年度
                        costTypeBudget.setYear(years.get(0));
                        if (fbParam != null)
                        {
                            if (fbParam.getYear() != null
                                    && !("".equals(fbParam.getYear())))
                            {
                                // 参数
                                costTypeBudget.setYear(fbParam.getYear());
                            }
                        }
                        // 地市
                        costTypeBudget.setCity(userInfoCity);
                        // 查询费用子类
                        List<Dictionary> subTypes = DatadicContext.getInstance()
                                .getSubDatadicByCode(costType.getId(), "FYLX");
                        // 子类预算
                        List<CostSubTypeBudget> costSubTypeBudgets = new ArrayList<CostSubTypeBudget>();
                        // 遍历
                        for (int j = 0; j < subTypes.size(); j++)
                        {
                            // 字典对象
                            Dictionary costSubType = subTypes.get(j);
                            // 实例化
                            CostSubTypeBudget costSubTypeBudget = new CostSubTypeBudget();
                            // 设置费用子类名称
                            costSubTypeBudget.setCostSubTypeName(costSubType.getDatavalue());
                            // 设置费用子类类型
                            costSubTypeBudget.setType(costSubType.getExtAttr1());
                            // 实例化参数对象
                            FundBudget fundBudget = new FundBudget();
                            // 设置费用类型id
                            fundBudget.setCostType(costType.getId()+"");
                            // 设置费用子类id
                            fundBudget.setCostSubtype(costSubType.getId()+"");
                            // 设置年度
                            fundBudget.setYear(costTypeBudget.getYear());
                            // 设置地市
                            fundBudget.setCity(costTypeBudget.getCity());
                            // 查询
                            CostSubTypeBudget returnCostSubTypeBudget = budgetListService.getSubTypeBudget(fundBudget,
                                    costSubType.getExtAttr1());
                            //
                            if (returnCostSubTypeBudget != null)
                            {
                                costSubTypeBudget.setId(returnCostSubTypeBudget.getId());
                                // 查询预算
                                if (returnCostSubTypeBudget.getBudget() == null
                                        || "".equals(returnCostSubTypeBudget.getBudget()))
                                {
                                    returnCostSubTypeBudget.setBudget("0");
                                }
                                costSubTypeBudget.setBudget(returnCostSubTypeBudget.getBudget());

                                if (totalCostSubTypeBudget.getBudget() == null
                                        || "".equals(totalCostSubTypeBudget.getBudget()))
                                {
                                    totalCostSubTypeBudget.setBudget("0");
                                }
                                // 累加
//                                totalCostSubTypeBudget.setBudget((Integer.valueOf(totalCostSubTypeBudget.getBudget()) + Integer.valueOf(costSubTypeBudget.getBudget()))
//                                        + "");
                            }
                            else
                            {
                                // 重置费用子类类型
                                costSubTypeBudget.setType(costSubTypeBudget.getType()
                                        + costSubTypeBudget.getType());
                                costSubTypeBudget.setBudget("0");
                            }
                            // 设置费用类型id
                            costSubTypeBudget.setCostType(costType.getId()+"");
                            // 设置费用子类id
                            costSubTypeBudget.setCostSubType(costSubType.getId()+"");
                            // 加入子类预算
                            costSubTypeBudgets.add(costSubTypeBudget);
                        }
                        // 设置子类预算size
                        costTypeBudget.setCostSubTypeBudgetsSize(subTypes.size());
                        // 设置子类预算
                        costTypeBudget.setCostSubTypeBudgets(costSubTypeBudgets);
                        // 加入预算
                        costTypeBudgets.add(costTypeBudget);
                    }
                    //
//                    totalCostSubTypeBudgets.add(totalCostSubTypeBudget);
                    //
                    totalCostTypeBudget.setCostSubTypeBudgets(totalCostSubTypeBudgets);
                    //
                    totalCostTypeBudget.setCostSubTypeBudgetsSize(totalCostSubTypeBudgets.size());
                    //
                    costTypeBudgets.add(totalCostTypeBudget);
                }
            }
            else
            {
                years = new ArrayList<String>();
            }

            // 重置返回值
            resultName = SUCCESS;
        }
        catch (Exception e)
        {
            // 打印异常信息
            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception BudgetListAction budgetList() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit BudgetListAction budgetList() method, return String");
        }
        return resultName;
    }

    /**
     * 预算子类列表
     * 
     * @return
     * @throws Exception
     */
    public String mediaBudgetList()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter BudgetListAction mediaBudgetList() method, return String");
        }

        try
        {
            // 年份
            years = budgetListService.getYearsByCity(sourcePlanYear.getCity());
            if (years != null)
            {
                if (years.size() != 0)
                {
                    if (sourcePlanYear == null)
                    {
                        sourcePlanYear = new SourcePlanYear2();
                        sourcePlanYear.setPlanYear(years.get(0));
                    }
                    // 获取总记录数
                    int totalRecords = budgetListService.getMediaBudgetCount(sourcePlanYear);
                    // 初始化分页对象
                    page = new PageBean(currentPage == 0 ? 1 : currentPage,
                            Constants.PAGE_SIZE);
                    // 设置分页对象总记录数
                    page.setTotalRecords(totalRecords);
                    // 查询
                    sourcePlanYears = budgetListService.getMediaBudgetList(sourcePlanYear,
                            page);

                    if (sourcePlanYears != null && !sourcePlanYears.isEmpty())
                    {
                        for (SourcePlanYear2 sourcePlanYear2 : sourcePlanYears)
                        {

                            // 费用类型
                            Dictionary dic = DatadicContext.getInstance()
                                    .getDatadicObject(sourcePlanYear2.getCostType(),
                                            "FYLX");
                            if (dic != null)
                            {
                                sourcePlanYear2.setCostType(dic.getDatavalue());
                            }

                            // 费用子类
                            dic = DatadicContext.getInstance()
                                    .getDatadicObject(sourcePlanYear2.getCostSubtype(),
                                            "FYLX");
                            if (dic != null)
                            {
                                sourcePlanYear2.setCostSubtype(dic.getDatavalue());
                            }
                        }
                    }
                }
            }
            else
            {
                years = new ArrayList<String>();
            }

            // 重置返回值
            resultName = SUCCESS;
        }
        catch (Exception e)
        {
            // 打印异常信息
            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception BudgetListAction mediaBudgetList() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit BudgetListAction mediaBudgetList() method, return String");
        }
        return resultName;
    }

    /**
     * 修改预算
     * 
     * @return
     * @throws Exception
     */
    public String modifyBudget()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter BudgetListAction modifyBudget() method, return String");
        }

        try
        {
            // 修改
            if (budgetListService.modifyBudget(fbParam))
            {
                HttpServletResponse response = ServletActionContext.getResponse();
                response.setContentType("text/html; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script type=\"text/javascript\">");
                out.println("alert(\"修改成功！\");");
                out.println("window.location.href='budgetList.action';");
                out.println("</script>");
                out.flush();
                out.close();
            }
            else
            {
                HttpServletResponse response = ServletActionContext.getResponse();
                response.setContentType("text/html; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script type=\"text/javascript\">");
                out.println("alert(\"修改失败！\");");
                out.println("window.location.href='budgetList.action';");
                out.println("</script>");
                out.flush();
                out.close();
            }
        }
        catch (Exception e)
        {
            // 打印异常信息
            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception BudgetListAction modifyBudget() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit BudgetListAction modifyBudget() method, return String");
        }
        return resultName;
    }

    /**
     * 删除预算
     * 
     * @return
     * @throws Exception
     */
    public String deleteBudget()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter BudgetListAction modifyBudget() method, return String");
        }

        try
        {
            // 修改
            if (budgetListService.deleteBudget(sourcePlanYear, null))
            {
                //
                UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                        .getSession()
                        .getAttribute(Constants.SESSIONPRKEY);
                // 日志记录
                String user = null;
                String cityCode = null;
                String cityName = null;
                String organizaOragName = null;
                if (null == userInfo)
                {
                    user = "张三";
                    cityName = "东莞";
                    organizaOragName = "市场部";
                    cityCode = "DG";
                }
                else
                {
                    user = userInfo.getUserName();
                    cityCode = userInfo.getUsercity();
                    cityName = userInfo.getCityName();
                    organizaOragName = userInfo.getOrganiza().getOrgName();
                }
                if (null == cityCode)
                {
                    cityCode = "";
                    cityName = "东莞";
                }
                Timestamp d = new Timestamp(System.currentTimeMillis());
                String content = d + " " + cityName + organizaOragName + user
                        + "删除了投放明细";
                String datatime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
                Date data = new Date(System.currentTimeMillis());
                /** 获取变更记录的数据 */
                Log logRecord = new Log("T_CB_PROJECTMEDIUM",
                        content,
                        sourcePlanYear.getId() + "",
                        datatime,
                        user,
                        cityCode,
                        organizaOragName,
                        "科室");

                optLogService.addLog(logRecord);
                //
                HttpServletResponse response = ServletActionContext.getResponse();
                response.setContentType("text/html; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script type=\"text/javascript\">");
                out.println("alert(\"删除成功！\");");
                String url = "mediaBudgetList.action?sourcePlanYear.planYear="
                        + sourcePlanYear.getPlanYear()
                        + "&sourcePlanYear.city=" + sourcePlanYear.getCity()
                        + "&sourcePlanYear.costType="
                        + sourcePlanYear.getCostType()
                        + "&sourcePlanYear.costSubtype="
                        + sourcePlanYear.getCostSubtype();
                out.println("window.location.href='" + url + "';");
                out.println("</script>");
                out.flush();
                out.close();
            }
            else
            {
                HttpServletResponse response = ServletActionContext.getResponse();
                response.setContentType("text/html; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println("<script type=\"text/javascript\">");
                out.println("alert(\"删除失败！\");");
                String url = "mediaBudgetList.action?sourcePlanYear.planYear="
                        + sourcePlanYear.getPlanYear()
                        + "&sourcePlanYear.city=" + sourcePlanYear.getCity()
                        + "&sourcePlanYear.costType="
                        + sourcePlanYear.getCostType()
                        + "&sourcePlanYear.costSubtype="
                        + sourcePlanYear.getCostSubtype();
                out.println("window.location.href='" + url + "';");
                out.println("</script>");
                out.flush();
                out.close();
            }
            // 重置返回值
            resultName = SUCCESS;
        }
        catch (Exception e)
        {
            // 打印异常信息
            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception BudgetListAction modifyBudget() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit BudgetListAction modifyBudget() method, return String");
        }
        return resultName;
    }

    public void setBudgetListService(BudgetListService budgetListService)
    {
        this.budgetListService = budgetListService;
    }

    public List<CostTypeBudget> getCostTypeBudgets()
    {
        return costTypeBudgets;
    }

    public List<String> getYears()
    {
        return years;
    }

    public FundBudget getFbParam()
    {
        return fbParam;
    }

    public void setFbParam(FundBudget fbParam)
    {
        this.fbParam = fbParam;
    }

    public void setSourcePlanYear(SourcePlanYear2 sourcePlanYear)
    {
        this.sourcePlanYear = sourcePlanYear;
    }

    public SourcePlanYear2 getSourcePlanYear()
    {
        return sourcePlanYear;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public List<SourcePlanYear2> getSourcePlanYears()
    {
        return sourcePlanYears;
    }

    public void setOptLogService(OptLogService optLogService)
    {
        this.optLogService = optLogService;
    }

}
